package com.alstudio.app;

import static android.os.Environment.MEDIA_MOUNTED;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.alstudio.event.ALEventDeliver;
import com.alstudio.module.voip.ALVoipMediaManager;
import com.alstudio.module.xmpp.protocol.xmpp.ALXmppAdapter;
import com.alstudio.module.xmpp.protocol.xmpp.ALXmppEventNotifyManager;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALDeviceInfo;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppData;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppEventType;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.protocol.xmpp.util.PackactIdGenerator;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.service.BackgroundService;
import com.alstudio.utils.account.ALAccount;
import com.alstudio.utils.account.ALAccountManager;
import com.alstudio.utils.account.UserProfileManager;
import com.alstudio.utils.android.AndroidUtils;
import com.alstudio.utils.android.device.ALDisplayMetricsManager;
import com.alstudio.utils.android.device.InstallInfo;
import com.alstudio.utils.android.media.ALMediaManager;
import com.alstudio.utils.android.media.audio.player.ALAudioPlayTask;
import com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.ALAudioPlayTaskCallback;
import com.alstudio.utils.android.net.ALConnectionManager;
import com.alstudio.utils.android.net.ALTelePhoneManager;
import com.alstudio.utils.android.net.ALWifiManager;
import com.alstudio.utils.android.notification.ALNotificationCenterManager;
import com.alstudio.utils.database.DatabaseUtil;
import com.alstudio.utils.formater.FileIdUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.notification.SystemNotificationEnvConfig;
import com.alstudio.utils.notification.SystemSettings;
import com.alstudio.utils.sp.ALSharedPreferencesManager;
import com.alstudio.view.image.ALRoundImageDisplayer;
import com.alstudio.view.toast.MyToastUtil;
import com.baidu.frontia.FrontiaApplication;
import com.loovee.LooveeLibManager;
import com.loovee.imaohu.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.L;

public class ALLocalEnv extends FrontiaApplication {

	public static ALXmppAdapter adapter;

	/* 此变量用于创建xmpp事件管理器，通过此管理器，驱动UI更新界面 */
	public static ALXmppEventNotifyManager mXmppEventNotifyManager;
	/* 版本信息 */
	public static final int LOAD_MORE_START_INDEX = 0;
	public static final int LOAD_MORE_END_INDEX = 19;
	public static final int LOAD_MORE_COUNT_PER_TIME = 20;

	public static ALLocalEnv instance;

	private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

	// 全圆图片显示配置
	private DisplayImageOptions cycleImageDisplayOptions;
	// 圆角图片显示配置
	private DisplayImageOptions roundImageDisplayOptions;

	// 普通房角图片显示
	private DisplayImageOptions normalImageDisplayOptions;

	// 大图头像
	private DisplayImageOptions largeImageIconDisplayOption;

	// 全局的布局1加载器
	private LayoutInflater mGlobalLayoutInflater;

	private VersionConfig mVersionConfig;
	// 账号密码
	private ALAccount myAccount;
	// 全局数据库
	private DatabaseUtil mDatabase;
	// 第一次使用
	private boolean isFirstUse = true;
	// 我的资料对象
	private User myProfile;

	// 设备唯一标识符
	private String imei;

	private String downloadUrl = "www.baidu.com";
	// 全局音频管理
	private ALMediaManager mAlMediaManager;
	// voip音频管理
	private ALVoipMediaManager mVoipMediaManager;

	// sp管理器
	private ALSharedPreferencesManager spManager;

	// 通知中心管理器
	private ALNotificationCenterManager mNotificationManager;

	// 音乐播放器
	private ALAudioPlayTask mAudioPlayTask;

	private boolean isNewVersionAlertShowed = false;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		ALLog.d("开启App" + LooveeLibManager.getLooveeLibManager().getHomePage());
		instance = this;
		// 初始化本地环境变量
		initLocalEnv();
		// 启动service
		startLocalService();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onLowMemory()
	 */
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		ImageLoader.getInstance().clearMemoryCache();
		ALLog.d("app low memory trim bitmap cache now!");
	}

	/**
	 * 初始化本地全局变量
	 * 
	 * @author alonso lee
	 */
	private void initLocalEnv() {
		// 上下文
		// 创建xmpp事件管理器
		mXmppEventNotifyManager = new ALXmppEventNotifyManager();
		// 版本控制
		mVersionConfig = new VersionConfig(this, true);
		// 初始化图片加载管理器
		initImageLoader(getApplicationContext());

		mGlobalLayoutInflater = (LayoutInflater) (getBaseContext())
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mDatabase = new DatabaseUtil();
		spManager = new ALSharedPreferencesManager(this);
		myProfile = UserProfileManager.loadMyProfile();

		mAlMediaManager = new ALMediaManager(this);

		mVoipMediaManager = new ALVoipMediaManager(this);
		mVoipMediaManager.setALMediaManager(mAlMediaManager);

		// 初始化通知中心
		mNotificationManager = new ALNotificationCenterManager(this);

		// 初始化语音播放器
		mAudioPlayTask = new ALAudioPlayTask(this, "", VersionConfig.AUDIO_PATH);
	}

	/**
	 * 初始化图片显示器配置项。配置
	 * 
	 * @param context
	 */
	private void initImageLoader(Context context) {
		// 初始化图片管理器全局配置
		File cacheDir = getCacheDirectory(context, VersionConfig.LOOVEE_DIR);
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).memoryCacheExtraOptions(480, 800)
		// default = device screen dimensions
				.discCache(new UnlimitedDiscCache(cacheDir)) // default
				.denyCacheImageMultipleSizesInMemory().writeDebugLogs().build();
		ImageLoader.getInstance().init(config);

		// 圆形图片显示配置
		cycleImageDisplayOptions = new DisplayImageOptions.Builder()
				./* delayBeforeLoading(1000). */cacheInMemory(true)
				// 加入内存缓存
				.cacheOnDisc(true)
				// 加入sd卡缓存
				.showImageOnLoading(R.drawable.personal_avatar_default)
				.showImageForEmptyUri(R.drawable.personal_avatar_default)
				.showImageOnFail(R.drawable.personal_avatar_default)
				.displayer(new ALRoundImageDisplayer(100)) // 圆形图片显示
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		// 圆角图片显示配置
		roundImageDisplayOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.call_user_bg_empty)
				.showImageForEmptyUri(R.drawable.call_user_bg_empty)
				.showImageOnFail(R.drawable.call_user_bg_empty)
				./* delayBeforeLoading(1000). */cacheInMemory(true)
				// 加入内存缓存
				.cacheOnDisc(true).imageScaleType(ImageScaleType.NONE)
				// default

				// 加入sd卡缓存
				.displayer(new ALRoundImageDisplayer(10))
				// 圆形图片显示
				// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		// 普通方形显示配置
		normalImageDisplayOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.find_bg_empty)
				.showImageForEmptyUri(R.drawable.find_bg_empty)
				.showImageOnFail(R.drawable.find_bg_empty).cacheInMemory(true)
				.cacheOnDisc(true)/* .considerExifParams(true) */
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(500, true, true, false))
				/* .displayer(new FadeInBitmapDisplayer(200)) */.build();

		// 大图显示配置
		largeImageIconDisplayOption = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.personal_default_bg)
				.showImageForEmptyUri(R.drawable.personal_default_bg)
				.showImageOnFail(R.drawable.personal_default_bg)
				.cacheInMemory(false).cacheOnDisc(true)/*
														 * .considerExifParams(true
														 * )
														 */
				.bitmapConfig(Bitmap.Config.RGB_565).build();

	}

	/**
	 * 启动后台服务
	 * 
	 * @author alonso lee
	 */
	private void startLocalService() {
		// Intent i = new Intent(this, BackgroundService.class);
		// startService(i);
	}

	/**
	 * 获取渠道名
	 * 
	 * @return
	 */
	public String getDownloadUrl() {
		return downloadUrl;
	}

	/**
	 * @return the myAccount
	 */
	public ALAccount getMyAccount() {
		return myAccount;
	}

	/**
	 * 获取全局的context
	 * 
	 * @return
	 */
	public Context getContext() {
		return getApplicationContext();
	}

	/**
	 * 获取application对象
	 * 
	 * @return
	 */
	public static ALLocalEnv getLocalEnv() {
		return instance;
	}

	/**
	 * 获取圆形图片显示配置文件
	 * 
	 * @return
	 */
	public DisplayImageOptions getCycleImageDisplayOptions() {
		return cycleImageDisplayOptions;
	}

	/**
	 * 获取圆角图片显示配置文件
	 * 
	 * @return
	 */
	public DisplayImageOptions getRoundImageDisplayOption() {
		return roundImageDisplayOptions;
	}

	/**
	 * 获取方向普通图片显示配置文件
	 * 
	 * @return
	 */
	public DisplayImageOptions getNormalRectImageDisplayOption() {
		return normalImageDisplayOptions;
	}

	/**
	 * 获取大头像图片显示配置文件
	 * 
	 * @return
	 */
	public DisplayImageOptions getLargeIconImageDisplayOption() {
		return largeImageIconDisplayOption;
	}

	/**
	 * 清除图片显示器内存中的图片缓存
	 */
	public void clearImageLoaderMemoryCache() {
		ImageLoader.getInstance().clearMemoryCache();
	}

	/**
	 * 清除图片显示器文件系统中的图片缓存
	 */
	public void clearImageLoaderDiskCache() {
		ImageLoader.getInstance().clearDiscCache();
	}

	/**
	 * 获取全局的布局加载器
	 * 
	 * @return
	 */
	public LayoutInflater getGlobalLayoutInflater() {
		return mGlobalLayoutInflater;
	}

	/**
	 * 获取图片管理器实例
	 * 
	 * @return
	 */
	public ImageLoader getImageLoader() {
		return ImageLoader.getInstance();
	}

	/**
	 * 显示图片
	 * 
	 * @param url
	 * @param view
	 * @param displayOption
	 */
	public void displayImage(String url, ImageView view,
			DisplayImageOptions displayOption) {

		view.setScaleType(ScaleType.CENTER_CROP);
		ALLocalEnv.getLocalEnv().getImageLoader()
				.displayImage(url, view, displayOption);
	}

	/**
	 * 显示图片
	 * 
	 * @param url
	 * @param view
	 */
	public void displayImage(String url, ImageView view) {
		ALLocalEnv.getLocalEnv().getImageLoader().displayImage(url, view);
	}

	/**
	 * 显示图片,调用此方法，会自动在传入的url基础上加入媒体服务器地址、图片下载serverlet
	 * 
	 * @param url
	 * @param view
	 */
	public void displayImagePluginServerlet(String fileid, ImageView view) {
		String url = createPhotoDownloadUrl(fileid);
		view.setScaleType(ScaleType.CENTER_CROP);
		ALLocalEnv.getLocalEnv().getImageLoader()
				.displayImage(url, view, normalImageDisplayOptions);
		// Picasso.with(this).load(url).into(view);
	}

	/**
	 * 显示图片,调用此方法，会自动在传入的url基础上加入媒体服务器地址、图片下载serverlet
	 * 
	 * @param url
	 * @param view
	 */
	public void displayImagePluginServerlet(String fileid,
			final ImageView view, DisplayImageOptions displayOption) {
		String url = createPhotoDownloadUrl(fileid);
		view.setScaleType(ScaleType.CENTER_CROP);
		// Picasso.with(this).setDebugging(true);
		// Picasso.with(this).load(url).into(view);

		ALLog.d("下载url " + url);
		// ImageAware imageAware = new ImageViewAware(view, false);
		// ALLocalEnv.getLocalEnv().getImageLoader().displayImage(url,
		// imageAware,displayOption);
		// url =
		// "http://i0.sinaimg.cn/ent/s/j/2008-04-08/U2231P28T3D1978904F326DT20080408183926.JPG";

		// view.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// displayImage(url, view, normalImageDisplayOptions);
		// }
		// });
		displayImage(url, view, displayOption);

	}

	/**
	 * 传入图片fileid，根据媒体服务器地址生成下载连接
	 * 
	 * @param fileid
	 * @return
	 */
	public String createPhotoDownloadUrl(String fileid) {
		fileid = FileIdUtils.getBareFileId(fileid);
		String url = "http://"
				+ ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
						.getMediaServerIp()
				+ ":"
				+ ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
						.getMediaServerPort()
				+ "/MediaServerMblove/servlet/PhotoServlet/" + fileid;
		return url;
	}

	public String createAudioDownloadUrl(String fileid) {
		fileid = FileIdUtils.getBareFileId(fileid);
		String url = "http://"
				+ ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
						.getMediaServerIp()
				+ ":"
				+ ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
						.getMediaServerPort()
				+ "/MediaServerMblove/servlet/Proxy/AudioServlet/" + fileid;
		return url;
	}

	/**
	 * 获取应用配置文件
	 * 
	 * @return
	 */
	public VersionConfig getVersionConfig() {
		return mVersionConfig;
	}

	/**
	 * 获取音频管理器实例
	 * 
	 * @return
	 */
	public ALMediaManager getMediaManager() {
		return mAlMediaManager;
	}

	/**
	 * 获取voip音频管理
	 * 
	 * @return
	 */
	public ALVoipMediaManager getVoipMediaManager() {
		return mVoipMediaManager;
	}

	/**
	 * 获取通知中心管理器F
	 * 
	 * @return
	 */
	public ALNotificationCenterManager getNotificationCenterManager() {
		return mNotificationManager;
	}

	/**
	 * 获取音频播放器
	 * 
	 * @return
	 */
	public ALAudioPlayTask getAudioPlayer() {
		return mAudioPlayTask;
	}

	/**
	 * 设置音频播放器回调
	 * 
	 * @param audioPlayCallback
	 */
	public void setAudioPlayerCallback(ALAudioPlayTaskCallback audioPlayCallback) {
		mAudioPlayTask.setAudioPlayCallback(audioPlayCallback);
	}

	/**
	 * 播放语音文件
	 * 
	 * @param fileid
	 */
	public void playAudio(String fileid) {
		mAudioPlayTask.setSavePath(VersionConfig.AUDIO_PATH);
		mAudioPlayTask.setFildId(FileIdUtils.getBareFileId(fileid));
		mAudioPlayTask.setAudioUrl(createAudioDownloadUrl(FileIdUtils
				.getBareFileId(mAudioPlayTask.getFildId())));
		mAudioPlayTask.Play();
	}

	/**
	 * 通知播放语音文件
	 */
	public void stopAudio() {
		mAudioPlayTask.stop();
	}

	/**
	 * 获取数据库实例
	 * 
	 * @return the mDatabase
	 */
	public DatabaseUtil getDatabase() {
		return mDatabase;
	}

	/**
	 * 设置账号
	 * 
	 * @param account
	 */
	public void setAccount(ALAccount account) {
		this.myAccount = account;
	}

	/**
	 * @return the myProfile
	 */
	public User getMyProfile() {
		return myProfile;
	}

	/**
	 * @param myProfile
	 *            the myProfile to set
	 */
	public void setMyProfile(User myProfile) {
		this.myProfile = myProfile;
	}

	/**
	 * 检测网络是否可用，如不可用，则打出toast提示
	 * 
	 * @return
	 */
	public static boolean isNetworkConnected() {
		if (!ALConnectionManager.isNetWorkConnected()) {
			MyToastUtil.getInstance().showCenterToastOnCenter(
					instance.getString(R.string.TxtNoDataConnection));
			return false;
		}
		return true;
	}

	/**
	 * 检测是否已经登录服务器
	 * 
	 * @return
	 */
	public static boolean isLogined() {
		if (ALLocalEnv.adapter != null && ALLocalEnv.adapter.isLogined())
			return true;
		MyToastUtil.getInstance().showCenterToastOnCenter(
				instance.getString(R.string.TxtLoging));
		return false;
	}

	/**
	 * 检测网络可用且已经登录到服务器
	 * 
	 * @return
	 */
	public static boolean isSendXmppDataEnable() {
		if (!isNetworkConnected())
			return false;
		if (!isLogined())
			return false;
		return true;
	}

	/**
	 * 获取sp管理器
	 * 
	 * @return
	 */
	public ALSharedPreferencesManager getSpManager() {
		return spManager;
	}

	/**
	 * 检测我的个人资料是否为空
	 * 
	 * @return
	 */
	public boolean isMyProfileEmpty() {
		return TextUtils.isEmpty(myProfile.getNick())
				|| TextUtils.isEmpty(myProfile.getJid());
	}

	/**
	 * 检测两个User对象是否一致。比对规则为判断jid是否一致
	 * 
	 * @param src
	 * @param dst
	 * @return
	 */
	public boolean isTheSameUser(User src, User dst) {
		if (src == null || dst == null)
			return false;
		if (src.getJid() == null && dst.getJid() == null)
			return false;
		if (src.getJid().equals(dst.getJid())) {
			return true;
		}
		return false;
	}

	/**
	 * 注销登陆或者异地登陆时,清除内存中的数据
	 */
	public void clearEnv() {
		// 清除事件监听器监听类
		// ALEventDeliver.clearCaches();
		// 清除内存中的图片
		ALLocalEnv.getLocalEnv().clearImageLoaderMemoryCache();
		// 清除本地个人资料
		myProfile = new User();
		UserProfileManager.saveMyProfile(myProfile);
		// 清除系统设置
		SystemSettings setting = new SystemSettings();
		SystemNotificationEnvConfig.getInstance().saveSystemSettings(setting);
		// 重新加载系统设置
		SystemNotificationEnvConfig.getInstance().reloadSystemSettings();
		// 修改账号，关闭数据库
		ALLocalEnv.getLocalEnv().getDatabase().saveSystemSetting(true);
		// 清除本地数据
		myAccount.setUserName("");
		myAccount.setPassWord("");

		mDatabase.saveMyAccount(myAccount);
		// 清除所有通知
		mNotificationManager.cancelAllNotification();
	}

	/**
	 * 通知界面销毁
	 */
	public void postFinishAllActivityEvent() {
		// 发消息关闭所有界面
		ALXmppEvent event = new ALXmppEvent(
				ALXmppEventType.XMPP_CLOSE_ACTIVITY_EVENT);
		ALEventDeliver.getDefaultAlEventDeliver().postALEvent(event);
	}

	/**
	 * 关闭程序
	 */
	public void closeApp() {
		postFinishAllActivityEvent();
		// 清除所有通知
		mNotificationManager.cancelAllNotification();
		// 退出登录
		ALUiXmppRequestCreator.postALUiXmppLogOutEvent();
		// 停止后台服务
		Intent service = new Intent(this, BackgroundService.class);
		stopService(service);

		System.exit(0);
	}

	/**
	 * 检测是否有版本更新,如果有版本更新，此方法只会返回一次为true
	 * 
	 * @return
	 */
	public boolean isNewVersionArrive() {
		if (!TextUtils.isEmpty(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getNewVersionUrl())) {
			if (!isNewVersionAlertShowed) {
				isNewVersionAlertShowed = true;
				ALLog.d("有版本更新");
				return true;
			}
		} else {
			// 没有新版本
			ALLog.d("没有新版本");
		}
		return false;
	}

	/**
	 * 检测是否有版本更新
	 * 
	 * @return
	 */
	public boolean isNewVersionAlert() {
		if (!TextUtils.isEmpty(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getNewVersionUrl())) {
			return true;
		} else {
			// 没有新版本
			ALLog.d("没有新版本");
		}
		return false;
	}

	/**
	 * 获取全局实用的head列表，用于打开网页
	 * 
	 * @return
	 */
	public HashMap<String, String> getDefaultWebHeads() {
		HashMap<String, String> headers = new HashMap<String, String>();

		// id(required) varchar(32) 请求ID号(10位随机数或字母) HEAD
		// username(required) varchar(100) 用户唯一ID（取自username） HEAD
		// token(required) varchar(64) 用户唯一标识（取自login_token） HEAD
		// language(required) varchar(32) 客户端语言(ch/fn/en/jp) HEAD
		// os(required) varchar(32) 客户端平台（android,ios） HEAD
		// version(required) varchar(32) APP版本 HEAD
		// id
		headers.put("id", PackactIdGenerator.getPackactIdGenerator()
				.getPackactId(10));
		headers.put("username", myAccount.getUserName());
		headers.put("token", myAccount.getToken());
		headers.put("language", getCurrentLanguage());
		headers.put("os", "android");
		headers.put("version", mVersionConfig.getAppVersion());
		return headers;
	}

	public static String getCurrentLanguage() {
		String locale = Locale.getDefault().getLanguage() + "-"
				+ Locale.getDefault().getCountry();
		locale = "en";
		String language = Locale.getDefault().getLanguage();
		String country = Locale.getDefault().getCountry();

		if (language.indexOf("zh") != -1) {
			locale = "fn";

			// 中文
			if (country.indexOf("CN") != -1) {
				locale = "ch";
			}
		}

		if (country.indexOf("JP") != -1) {
			locale = "jp";
		}
		return locale;
	}

	/**
	 * 创建待发送的ALMessage对象
	 * 
	 * @return
	 */
	public ALMessage createMessage() {
		ALMessage message = new ALMessage();
		// fromjid
		message.setFrom(myProfile.getJid());
		// nick
		message.setFromNick(myProfile.getNick());
		// time
		message.setDate((new Date(System.currentTimeMillis())));
		// 头像
		message.setFromAvatar(myProfile.getThumbAvatar());

		message.setDisplayed(true);

		message.getMsgId();

		message.setSex(myProfile.getSex());
		message.setVauth(myProfile.getVauthed() + "");
		return message;
	}

	/**
	 * 创建发送给指定用户的ALMessage对象
	 * 
	 * @param user
	 * @return
	 */
	public ALMessage createMessage(User user) {
		if (user == null)
			return null;
		ALMessage message = createMessage();
		message.setTo(user.getJid());
		message.setJid(user.getJid());
		message.setToNick(user.getNick());
		return message;
	}

	/**
	 * 创建发送给指定用户的ALMessage对象
	 * 
	 * @param user
	 * @return
	 */
	public ALMessage createMessage(User user, int type) {
		if (user == null)
			return null;
		ALMessage message = createMessage();
		message.setTo(user.getJid());
		message.setJid(user.getJid());
		message.setToNick(user.getNick());
		message.setType(type);
		return message;
	}

	/**
	 * 快速创建ALXmppData对象，内涵服务器地址、端口、域名、软件版本号、下载渠道、imei、uuid、sdk版本、设备型号、android id
	 * uuid
	 * 
	 * @return
	 */
	public ALXmppData createALXmppData() {
		ALXmppData data = new ALXmppData();
		// 服务器地址
		data.setHost(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getIMServerIP());

		// 服务器端口
		data.setPort(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getIMSocketPort());
		// 域名
		data.setDomain(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getServerName());

		// 软件版本号
		data.setAppVersion(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getAppVersion());

		data.setImei(getIMEI());
		data.setUuid(getDeviceUuid());

		data.setNetType(ALConnectionManager.getConnectionTypeString());

		data.setDownloadUrl(downloadUrl);

		ALDeviceInfo info = new ALDeviceInfo();
		// sdk版本
		info.setSdkVersion(AndroidUtils.getSystemSdkVersion());
		// model手机设备名
		info.setDeviceModel(AndroidUtils.getDeviceModel());
		// android id
		info.setAndroidId(getAndroidId());
		// uuid
		info.setUuid(getDeviceUuid());

		// 手机高宽度
		info.setScreenHeight(ALDisplayMetricsManager.getScreenHeight(ALLocalEnv
				.getLocalEnv()) + "");
		info.setScreeWidth(ALDisplayMetricsManager.getScreenWidth(ALLocalEnv
				.getLocalEnv()) + "");

		data.setDevInfo(info);
		return data;
	}

	/**
	 * 返回手机IMEI号。
	 * 
	 * @return 手机IMEI号
	 * @author Alonso Lee
	 */
	protected String getIMEI() {
		if (imei != null) {
			return imei;
		} else {

			imei = ALTelePhoneManager.getImei(ALLocalEnv.getLocalEnv());

			if (TextUtils.isEmpty(imei)
					&& ALWifiManager.getMacAddress(ALLocalEnv.getLocalEnv()) != null) {
				imei = ALWifiManager.getMacAddress(ALLocalEnv.getLocalEnv());
				ALLog.d("wifi mac: " + imei);
			}

			if (imei == null) {
				imei = "";
			}
			return imei;
		}
	}

	protected String getWifiMac() {
		String mac = ALWifiManager.getMacAddress(ALLocalEnv.getLocalEnv());
		if (TextUtils.isEmpty(mac)) {
			mac = "";
		}
		return mac;
	}

	/**
	 * 获取Android唯一标识符
	 * 
	 * @return
	 */
	protected String getAndroidId() {
		String androidId = Settings.Secure.getString(ALLocalEnv.getLocalEnv()
				.getContentResolver(), Settings.Secure.ANDROID_ID);

		if (TextUtils.isEmpty(androidId)) {
			androidId = "";
		}
		return androidId;
	}

	/**
	 * 获取设备UUID
	 * 
	 * @return
	 */
	protected String getDeviceUuid() {

		InstallInfo installInfo = new InstallInfo();
		String res = installInfo.id(ALLocalEnv.getLocalEnv());
		if (TextUtils.isEmpty(ALAccountManager.checkAccountTrace("alonso"))) {
			ALAccountManager.makeAccountTrace("alonso", res);
		} else {
			res = ALAccountManager.checkAccountTrace("alonso");
		}

		if (res == null) {
			res = "";
		}
		ALLog.d("uuid: " + res);
		return res;
	}

	/**
	 * 從Jid中提出完整id
	 * 
	 * @param jid
	 * @return
	 */
	public static String getBareJid(String jid) {

		if (TextUtils.isEmpty(jid))
			return "";
		if (!jid.contains("@"))
			return jid;
		String jid2 = "";
		if (jid != null && jid.length() > 0) {
			int index = jid.indexOf("@");
			jid2 = jid.substring(0, index);
		}

		return jid2;
	}

	/**
	 * 获取文件file id
	 * 
	 * @param url
	 * @return
	 */
	public static String getBareFileId(String url) {
		String s = null;

		if (TextUtils.isEmpty(url)) {
			return s;
		}
		if (!url.contains("http://")) {
			return url;
		}

		if (url.length() > 0) {
			try {
				s = url.substring(url.indexOf("fileid=") + 7);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return s;
	}

	private File getCacheDirectory(Context context, String path) {
		File appCacheDir = null;
		if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				&& hasExternalStoragePermission(context)) {
			// appCacheDir = getExternalCacheDir(context);
			appCacheDir = getExternalCacheDir(context, path, "images");

		}
		if (appCacheDir == null) {
			appCacheDir = context.getCacheDir();
		}
		if (appCacheDir == null) {
			String cacheDirPath = "/data/data/" + context.getPackageName()
					+ "/cache/";
			L.w("Can't define system cache directory! '%s' will be used.",
					cacheDirPath);
			appCacheDir = new File(cacheDirPath);
		}
		return appCacheDir;
	}

	private boolean hasExternalStoragePermission(Context context) {
		int perm = context
				.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
		return perm == PackageManager.PERMISSION_GRANTED;
	}

	private File getExternalCacheDir(Context context) {
		File dataDir = new File(new File(
				Environment.getExternalStorageDirectory(), "Android"), "data");
		File appCacheDir = new File(
				new File(dataDir, context.getPackageName()), "cache");
		if (!appCacheDir.exists()) {
			if (!appCacheDir.mkdirs()) {
				L.w("Unable to create external cache directory");
				return null;
			}
			try {
				new File(appCacheDir, ".nomedia").createNewFile();
			} catch (IOException e) {
				L.i("Can't create \".nomedia\" file in application external cache directory");
			}
		}
		return appCacheDir;
	}

	private File getExternalCacheDir(Context context, String path, String dir) {
		File dataDir = new File(Environment.getExternalStorageDirectory(), path);
		File appCacheDir = new File(dataDir, dir);
		if (!appCacheDir.exists()) {
			if (!appCacheDir.mkdirs()) {
				L.w("Unable to create external cache directory");
				return null;
			}
			try {
				new File(appCacheDir, ".nomedia").createNewFile();
			} catch (IOException e) {
				L.i("Can't create \".nomedia\" file in application external cache directory");
			}
		}
		return appCacheDir;
	}

}
